<?php

declare(strict_types=1);

namespace App\Admin\Service\System;

use App\Admin\Mapper\System\SystemUploadFileMapper;
use Newbie\Abstracts\AbstractService;
use Newbie\NewbieUpload;
use Webman\Http\UploadFile;

/**
 * 文件上传业务
 * Class SystemLoginLogService
 * @package App\system\Service
 */
class SystemUploadFileService extends AbstractService {
    /**
     * @var SystemUploadFileMapper
     */
    public $mapper;

    /**
     * @var NewbieUpload
     */
    protected NewbieUpload $mineUpload;


    public function __construct (SystemUploadFileMapper $mapper, NewbieUpload $mineUpload) {
        $this->mapper     = $mapper;
        $this->mineUpload = $mineUpload;
    }

    /**
     * 上传文件
     * @param UploadFile $uploadedFile
     * @param array $config
     * @return array
     */
    public function upload (UploadFile $uploadedFile, array $config = []): array {
        $data = $this->mineUpload->upload($uploadedFile, $config);
        if ($this->save($data)) {
            return $data;
        } else {
            return [];
        }
    }

    /**
     * 获取当前目录下所有文件（包含目录）
     * @param array $params
     * @return array
     */
    public function getAllFile (array $params = []): array {
        return $this->getArrayToPageList($params);
    }

    /**
     * 数组数据搜索器
     * @param  $collect
     * @param array $params
     * @return mixed
     */
    protected function handleArraySearch ($collect, array $params) {
        if ($params['name'] ?? false) {
            $collect = $collect->filter(function ($row) use ($params) {
                return \newbie\Helper\Str::contains($row['name'], $params['name']);
            });
        }

        if ($params['label'] ?? false) {
            $collect = $collect->filter(function ($row) use ($params) {
                return \newbie\Helper\Str::contains($row['label'], $params['label']);
            });
        }
        return $collect;
    }

    /**
     * 设置需要分页的数组数据
     * @param array $params
     * @return array
     */
    protected function getArrayData (array $params = []): array {
        $directory        = $this->getDirectory($params['storage_path'] ?? '');
        $params['select'] = [
            'id',
            'origin_name',
            'object_name',
            'mime_type',
            'url',
            'size_info',
            'storage_path',
            'created_at'
        ];
        $params['select'] = implode(',', $params['select']);
        return array_merge($directory, $this->getList($params));
    }

    /**
     * 保存网络图片
     * @param array $data ['url', 'path']
     * @return array
     */
    public function saveNetworkImage (array $data): array {
        $data = $this->mineUpload->handleSaveNetworkImage($data);
        if ($this->save($data)) {
            return $data;
        } else {
            return [];
        }
    }
}
